package review.data_structure;

import java.util.Arrays;

/**
 * @author haomin
 * @date 2022/10/26 20:31
 **/
public class MyArray {
    private int[] arr;
    private int size;
    MyArray(){
        arr = new int[10];
        size = 0;
    }
    MyArray(int len){
        arr = new int[len];
        size = 0;
    }

    // 1. 增加
    public void addFirst(int val){
        addIndex(0, val);
    }
    public void addLast(int val){
        addIndex(size, val);
    }

    public void addIndex(int index,int val){
        //判断数组是否满
        if(size==arr.length){
            grow();
        }
        //判断index是否合法
        if(index<0||index>size){
            System.out.println("add index illegal!");
            return;
        }
        else{
            //将index位置空出
            for (int i = size-1; i >= index; i--) {
                arr[i+1]=arr[i];
            }
            arr[index]=val;
            size++;
        }
    }

    // 2. 查找
    public int searchVal(int index){
        if(index < 0 || index >= size){
            throw new IndexOutOfBoundsException("数值下标越界");
        }
        return arr[index];
    }
    public int searchIndex(int val){
        for(int i = 0; i < size; ++i){
            if(arr[i] == val) return i;
        }
        return -1;
    }

    // 3. 更新
    public void update(int index, int val){
        if(index < 0 || index >= size){
            throw new IndexOutOfBoundsException("数值下标越界");
        }
        arr[index] = val;
    }

    // 4. 删除
    public void deleteFirst(){
        deleteIndex(0);
    }
    public void deleteLast(){
        deleteIndex(size-1);
    }
    public void deleteOneVal(int val){
        for(int i = 0; i < size; ++i){
            if(arr[i] == val){
                deleteIndex(i);
                break;
            }
        }
    }
    public void deleteAllVal(int val){
        for(int i = 0; i < size; ++i){
            while (arr[i] == val){
                deleteIndex(i);
            }
        }
    }
    public void deleteIndex(int index){
        if(index < 0 || index >= size){
            throw new IndexOutOfBoundsException("数组下标越界");
        }
        for(int i = index; i < size-1; ++i) {
            arr[i] = arr[i + 1];
        }
        arr[size-1] = 0;
        size--;
    }

    // 5. 数组扩容
    private void grow() {
        int[] newArr = Arrays.copyOf(arr, arr.length << 1);
        arr = newArr;
    }

    // 6. 输出
    @Override
    public String toString() {
        return "MyArray{" +
                "arr=" + Arrays.toString(arr) +
                ", size=" + size +
                '}';
    }
}
